﻿namespace Proto.Providers
{
    using System;
    using System.Text;

    using Proto.Fields;

    public class Position : IFieldGetter
    {
        internal static int REF_COUNT = 0;
        ~Position()
        {
            REF_COUNT--;
        }

        public static readonly FieldSet m_FIELDSET = new FieldSet(
            FieldID.BookCode,FieldID.RIC,FieldID.Quantity
            );

        private readonly BookCode m_BookCode;
        private readonly RIC m_RIC;
        private Quantity m_Quantity;

        private readonly IKey m_Key;

        public Position(BookCode bookCode, RIC ric, Quantity quantity)
        {
            REF_COUNT++;

            m_BookCode = bookCode;
            m_RIC = ric;
            m_Quantity = quantity;
            m_Key = new QuickKey(new FieldSet(FieldID.RIC, FieldID.BookCode), this);
        }

        
        public BookCode BookCode
        {
            get
            {
                return this.m_BookCode;
            }
        }

        public RIC RIC{ get{ return this.m_RIC; } }

        public Quantity Quantity{ get{ return this.m_Quantity; } internal set
        {
            m_Quantity = value;
        }}

        public IKey Key{ get{ return m_Key; } }


        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (FieldID field in m_FIELDSET.Fields)
            {
                sb.Append(field).Append(':').Append(Get(field)).Append(',');
            }
            return sb.ToString();
        }

        public FieldSet FieldSet
        {
            get
            {
                return m_FIELDSET;
            }
        }

        public object Get( FieldID id )
        {
            switch (id)
            {
                case (FieldID.RIC): return m_RIC;
                case (FieldID.BookCode): return m_BookCode;
                case (FieldID.Quantity): return m_Quantity;
                default: throw new IndexOutOfRangeException(id.ToString() + " not contained by Position");
            }
        }

        public bool Get<T>(FieldID id, out T value)
        {
            object val = Get(id);
            if( val is T )
            {
                value = (T)val;
                return true;
            }
            value = default(T);
            return false;
        }
    }
}